package models.chat.engines;

import controllers.chat.ChatWS;
import controllers.chat.IdPair;
import models.ApplicationUser;
import models.chat.Channel;
import play.jobs.Every;
import play.jobs.Job;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Konovalov_Nik
 */
//@Every("30s")
//disabled
public class CleanChannelsJob extends Job {
    @Override
    public void doJob() throws Exception {
        List<Channel> channels = Channel.findAll();
        for (Channel channel : channels) {
            for (Long memberId : new ArrayList<Long>(channel.memberIds)) {
                if (!ChatWS.toClientMessages.containsKey(new IdPair(memberId, channel.id))) {
                    channel.memberIds.remove(memberId);
                    ApplicationUser member = ApplicationUser.findById(memberId);
                    member.channelIds.remove(channel.id);
                    member.save();
                }
            }
            channel.save();
        }
    }
}
